<template>
  <div class="add-card">
    <header class="add-header">
      <el-page-header
        :content="getTypeContent()"
        @back="$router.back()"
      />
    </header>
    <main class="add-main">
      <div class="form-container">
        <div class="title">车辆信息</div>
        <div class="form">
          <el-form
            ref="carInfoForm"
            :model="carInfoForm"
            :rules="carInfoRules"
            label-width="100px"
          >
            <el-form-item label="车主姓名" prop="personName">
              <el-input v-model="carInfoForm.personName" :disabled="isRenew" />
            </el-form-item>
            <el-form-item label="联系方式" prop="phoneNumber">
              <el-input v-model="carInfoForm.phoneNumber" :disabled="isRenew" />
            </el-form-item>
            <el-form-item label="车辆号码" prop="carNumber">
              <el-input
                v-model="carInfoForm.carNumber"
                :disabled="isRenew"
                @input="handleCarNumberInput"
              />
            </el-form-item>
            <el-form-item label="车辆品牌" prop="carBrand">
              <el-input v-model="carInfoForm.carBrand" :disabled="isRenew" />
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div class="form-container">
        <div class="title">{{ getTypeContentTitle() }}</div>
        <div class="form">
          <el-form
            ref="feeForm"
            :model="feeForm"
            :rules="feeFormRules"
            label-width="100px"
          >
            <el-form-item label="有效日期" prop="payTime">
              <el-date-picker
                v-model="feeForm.payTime"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              />
            </el-form-item>
            <el-form-item label="支付金额" prop="paymentAmount">
              <el-input v-model="feeForm.paymentAmount" />
            </el-form-item>
            <el-form-item label="支付方式" prop="paymentMethod">
              <el-select v-model="feeForm.paymentMethod">
                <el-option
                  v-for="item in payMethodList"
                  :key="item.id"
                  :value="item.id"
                  :label="item.name"
                />
              </el-select>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </main>
    <footer class="add-footer">
      <div class="btn-container">
        <el-button @click="resetForm">重置</el-button>
        <el-button type="primary" @click="confirmAdd">确定</el-button>
      </div>
    </footer>
  </div>
</template>

<script>
import { createCardAPI, getCardDetailAPI, updateCardAPI, renewCardAPI } from '@/api/card.js'

export default {
  data() {
    const validateCarNumber = (rule, value, callback) => {
      const regex =
        /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-HJ-NP-Z][A-HJ-NP-Z0-9]{4,5}[A-HJ-NP-Z0-9挂学警港澳]$/
      regex.test(value) ? callback() : callback(new Error('请输入规范车牌号'))
    }

    return {
      id: this.$route.query.id,
      type: this.$route.query.type,
      isRenew: false,
      carInfoForm: {
        personName: '',
        phoneNumber: '',
        carNumber: '',
        carBrand: '',
        carInfoId: ''
      },
      carInfoRules: {
        personName: [
          { required: true, message: '请输入车主姓名', trigger: 'blur' }
        ],
        phoneNumber: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          {
            pattern: /^1[3-9]\d{9}$/,
            message: '手机号格式错误',
            trigger: 'blur'
          }
        ],
        carNumber: [
          { required: true, message: '请输入车牌号', trigger: 'blur' },
          { validator: validateCarNumber, trigger: 'blur' }
        ],
        carBrand: [
          { required: true, message: '请输入车辆品牌', trigger: 'blur' }
        ]
      },
      feeForm: {
        payTime: [],
        paymentAmount: null,
        paymentMethod: '',
        rechargeId: ''
      },
      feeFormRules: {
        payTime: [
          { required: true, message: '请选择有效期', trigger: 'change' }
        ],
        paymentAmount: [
          { required: true, message: '请输入金额', trigger: 'blur' }
        ],
        paymentMethod: [
          { required: true, message: '请选择方式', trigger: 'change' }
        ]
      },
      payMethodList: [
        { id: 'Alipay', name: '支付宝' },
        { id: 'WeChat', name: '微信' },
        { id: 'Cash', name: '线下' }
      ]
    }
  },
  mounted() {
    if (this.id) {
      this.getDetail()
    }
    this.isRenew = this.type === 'renew' // 设置 isRenew 属性
  },
  beforeDestroy() {
    // 组件销毁前清空表单数据
    this.carInfoForm = {
      personName: '',
      phoneNumber: '',
      carNumber: '',
      carBrand: '',
      carInfoId: ''
    }
    this.feeForm = {
      payTime: [],
      paymentAmount: null,
      paymentMethod: '',
      rechargeId: ''
    }
  },
  methods: {
    // 提交表单
    async confirmAdd() {
      const [validCar, validFee] = await Promise.all([
        new Promise((resolve) => this.$refs.carInfoForm.validate(resolve)),
        new Promise((resolve) => this.$refs.feeForm.validate(resolve))
      ])
      if (!validCar || !validFee) return
      if (this.type === 'renew') {
        // 续费逻辑，只需要特定字段
        const payload = {
          carInfoId: this.carInfoForm.carInfoId,
          cardStartDate: this.feeForm.payTime[0],
          cardEndDate: this.feeForm.payTime[1],
          paymentAmount: this.feeForm.paymentAmount,
          paymentMethod: this.feeForm.paymentMethod
        }
        await renewCardAPI(payload)
      } else {
        // 新增和编辑逻辑保持不变
        const payload = {
          ...this.feeForm,
          ...this.carInfoForm,
          cardStartDate: this.feeForm.payTime[0],
          cardEndDate: this.feeForm.payTime[1]
        }
        delete payload.payTime
        if (!this.id) {
          delete payload.rechargeId
          delete payload.carInfoId
        }

        if (this.id) {
          await updateCardAPI(payload)
        } else {
          await createCardAPI(payload)
        }
      }

      this.$message.success('操作成功')
      this.$router.back()
    },
    // 获取详情
    async getDetail() {
      const res = await getCardDetailAPI(this.id)
      // 回填车辆信息表单
      const { carInfoId, personName, phoneNumber, carNumber, carBrand } = res.data
      this.carInfoForm = {
        personName, phoneNumber, carNumber, carBrand, carInfoId
      }

      // 根据类型处理缴费信息表单
      if (this.type === 'renew') {
        // 续费时，只保留开始时间，其他清空
        this.feeForm = {
          rechargeId: '',
          paymentAmount: '',
          paymentMethod: '',
          payTime: [res.data.cardEndDate, ''] // 以原结束时间作为新的开始时间
        }
      } else {
        // 编辑时，正常回填所有数据
        const { rechargeId, cardStartDate, cardEndDate, paymentAmount, paymentMethod } = res.data
        this.feeForm = {
          rechargeId,
          paymentAmount,
          paymentMethod,
          payTime: [cardStartDate, cardEndDate]
        }
      }
    },
    getTypeContent() {
      if (this.type === 'renew') {
        return '续费月卡'
      } else if (this.id) {
        return '编辑月卡'
      } else {
        return '增加月卡'
      }
    },
    getTypeContentTitle() {
      if (this.type === 'renew') {
        return '月卡缴费信息'
      } else if (this.id) {
        return '最新一次月卡缴费信息'
      } else {
        return '最新一次月卡缴费信息'
      }
    }
  },
  resetForm() {
    this.$refs.carInfoForm?.resetFields()
    this.$refs.feeForm?.resetFields()
  }
}
</script>

<style scoped lang="scss">
.add-card {
  background-color: #f4f6f8;
  height: 100vh;

  .add-header {
    display: flex;
    align-items: center;
    padding: 0 20px;
    height: 64px;
    background-color: #fff;
  }

  .add-main {
    background: #f4f6f8;
    padding: 20px 130px;

    .form-container {
      background-color: #fff;

      .title {
        height: 60px;
        line-height: 60px;
        padding-left: 20px;
      }

      .form {
        margin-bottom: 20px;
        padding: 20px 65px 24px;

        .el-form {
          display: flex;
          flex-wrap: wrap;

          .el-form-item {
            width: 50%;
          }
        }
      }
    }
  }

  .add-footer {
    position: fixed;
    bottom: 0;
    width: 100%;
    padding: 24px 50px;
    color: #000000d9;
    font-size: 14px;
    background: #fff;
    text-align: center;
  }
}
</style>
